package com.apes.enquiry.product.service;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.enquiry.product.model.BrandUploading;
import com.apes.enquiry.product.model.ReplacementProduct;
import com.apes.enquiry.product.repository.BrandUploadingRepository;
import com.apes.enquiry.product.repository.ProductDao;
import com.apes.enquiry.product.repository.ReplacementProductRepository;
import com.apes.enquiry.product.repository.SpProductRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MD5Util;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.rbac.model.User;
import com.apes.scm.rbac.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
public class BrandUploadingService extends DomainService {

    @Autowired
    private BrandUploadingRepository brandUploadingRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PartyRoleRepository partyRoleRepository;


    @Autowired
    private ProductDao productDao;


    /**
     * 动态条件查询
     * @param request
     * @return
     */
    public List<BrandUploading> conditionQuery(SimpleRequest request){
        JSONObject jo = request.getJO();
        User user = userRepository.findOne(Integer.valueOf(request.getSession().getUserId()));
        PartyRole supplier = partyRoleRepository.findOne(user.getPerson().getId());
        return brandUploadingRepository.findAll(JpaDsl.toCriteriaIgnoreNull("brandId", "EQ", jo.getString("brandId"),
                "pn", "EQ", jo.getString("pn"),
                "automobile","EQ",jo.getString("automobile"),
                "brand", "EQ", jo.getString("brand"),
                "supplier", "EQ", supplier
        ));

    }

    /**
     * 批量删除
     * @param request
     * @return
     */
    public List<BrandUploading> delBrandUploading(SimpleRequest request){
        List<BrandUploading> brandUploadings = request.getA("del", BrandUploading.class);
        brandUploadings.forEach(brandUploading -> {
            if (Objects.nonNull(brandUploading.getId())){
                brandUploadingRepository.delete(brandUploading);
            }
        });
        return conditionQuery(request);
    }


    /**
     * 品牌件关系上传
     * @param request
     * @return
     */
    public JSONObject importBrandUploading(SimpleRequest request){
        //Excel信息
        JSONObject importData = request.get("importData");
        JSONArray titleColumnArray = new JSONArray();
        User user = userRepository.findOne(Integer.parseInt(request.getSession().getUserId()));
        String key = appendImportReturn_New(importData, titleColumnArray,user);
        JSONObject returnData = new JSONObject();
        returnData.put(key, titleColumnArray);
        return returnData;
    }

    /**
     * 并行流导入
     * @param importData
     * @param titleColumnArray
     * @return
     */
    private String appendImportReturn_New(JSONObject importData, JSONArray titleColumnArray,User user) {

        AtomicReference<String> key = new AtomicReference<>();
        Set<String> stringHashSet = new HashSet<>();
        JSONArray titleArray = new JSONArray(4);
        titleArray.add("品牌件号");
        titleArray.add("品牌");
        titleArray.add("车品牌");
        titleArray.add("原厂零件号");
        titleColumnArray.add(titleArray);
        List<BrandUploading> brandUploadingList = Collections.synchronizedList(new ArrayList());
        importData.forEach((k, v) -> {
            key.set(k);
            JSONArray importDataValueArray = (JSONArray) v;
            importDataValueArray.parallelStream().forEach( item -> {
                BrandUploading brandUploading = new BrandUploading();
                JSONArray iValueArray = (JSONArray) item;
                if (iValueArray.size() < 4) throw new RuntimeException("导入失败，必填字段不能为空！");
                String brandId = "";
                String brand = "";
                String automobile = "";
                String pn  = "";
                for (int i = 0; i < iValueArray.size(); i++) {
                    if (Objects.isNull(iValueArray.get(i))) continue;
                    switch (i) {
                        case 0:
                            brandId = iValueArray.getString(0);
                            break;
                        case 1:
                            brand = iValueArray.getString(1);
                            break;
                        case 2:
                            automobile = iValueArray.getString(2);
                            break;
                        case 3:
                            pn = iValueArray.getString(3);
                            break;

                    }
                }

                if ("品牌件号".equals(brandId) && "原厂零件号".equals(pn)) {    // 匹配中英文
                    return;
                }
                if (!stringHashSet.add(brandId + automobile + brand+pn)) throw new RuntimeException("导入重复数据，请重新导入！");
                brandUploading.setBrandId(brandId);
                brandUploading.setAutomobile(automobile);
                brandUploading.setBrand(brand);
                brandUploading.setPn(pn);
                brandUploading.setSupplier(user.getPerson());
                brandUploadingList.add(brandUploading);
            });
        });

            productDao.brandUploadingInsert(brandUploadingList);
        return key.get();
    }



}
